package net.ecpt.hrm.services;


import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.wvtools.utils.ExcelPoiUtils;

import javolution.util.FastList;
import javolution.util.FastMap;

public class HrOfferXlsServices {
    public static final String module = HrOfferXlsServices.class.getName();


    /**
     * 导入
     */
    public static Map<String, Object> importXls(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
	Delegator delegator = dctx.getDelegator();
	List<GenericValue> toBeStore = new ArrayList();
	List<String> messageList = new ArrayList<String>();
	List<Map<String, Object>> sheetList = (List<Map<String, Object>>) context.get("sheetList");
	LocalDispatcher dispatcher = dctx.getDispatcher();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String createBy = userLogin.getString("partyId");

	try {
	    int i = 0;
	   
	    for (Map<String, Object> row : sheetList) {
		i = i + 1;
		
			String id = ExcelPoiUtils.getCellString(row, 0);
			String candidateId_dictText = ExcelPoiUtils.getCellString(row, 1);
			String departmentId_dictText = ExcelPoiUtils.getCellString(row, 2);
			String position_dictText = ExcelPoiUtils.getCellString(row, 3);
			String contractPeriod = ExcelPoiUtils.getCellString(row, 4);
			String probationPeriod = ExcelPoiUtils.getCellString(row, 5);
			String workingHours_dictText = ExcelPoiUtils.getCellString(row, 6);
			String annualSalary = ExcelPoiUtils.getCellString(row, 7);
			String monthlySalary = ExcelPoiUtils.getCellString(row, 8);
			String arrivalTime = ExcelPoiUtils.getCellString(row, 9);
			//应聘者,部门,职位,合同期（年）,试用期（月）,工时方式,年薪,月薪,预期报到日期
			
			
			
			// 判断
			if (UtilValidate.isEmpty(candidateId_dictText)) {
			    messageList.add("第" + (i + 1) + "行,应聘者不能为空。");
			    continue;
			}

			// 判断
			if (UtilValidate.isEmpty(departmentId_dictText)) {
			    messageList.add("第" + (i + 1) + "行,部门不能为空。");
			    continue;
			}
			// 判断
			if (UtilValidate.isEmpty(position_dictText)) {
			    messageList.add("第" + (i + 1) + "行,职位不能为空。");
			    continue;
			}
			// 判断
			if (UtilValidate.isEmpty(contractPeriod)) {
						    messageList.add("第" + (i + 1) + "行,合同期（年）不能为空。");
						    continue;
			}
			// 判断
			if (UtilValidate.isEmpty(probationPeriod)) {
			    messageList.add("第" + (i + 1) + "行,试用期（月）不能为空。");
			    continue;
			}
			// 判断
			if (UtilValidate.isEmpty(workingHours_dictText)) {
			    messageList.add("第" + (i + 1) + "行,工时方式不能为空。");
			    continue;
			}

			if (UtilValidate.isEmpty(annualSalary)) {
			    messageList.add("第" + (i + 1) + "行,年薪不能为空。");
			    continue;
			}
			
			if (UtilValidate.isEmpty(monthlySalary)) {
			    messageList.add("第" + (i + 1) + "行,月薪不能为空。");
			    continue;
			}
			
			if (UtilValidate.isEmpty(arrivalTime)) {
			    messageList.add("第" + (i + 1) + "行,预期报到日期不能为空。");
			    continue;
			}

			
			// 创建
			GenericValue entity = null;
			if (UtilValidate.isNotEmpty(id)) {
			   
			    List<GenericValue> entityList = delegator.findByAnd("HrOffer",
					    UtilMisc.toMap("id", id), null, false);
				    entity = EntityUtil.getFirst(entityList);
				if (UtilValidate.isEmpty(entity)) {
						 id = delegator.getNextSeqId("HrOffer");
						 entity = delegator.makeValue("HrOffer", UtilMisc.toMap("id", id));
						 entity.set("statusId", "0");
							entity.set("createBy", createBy);
							entity.set("createDate", nowTimestamp);
						} 
					   
			}else  {
			    id = delegator.getNextSeqId("HrOffer");
			    entity = delegator.makeValue("HrOffer", UtilMisc.toMap("id", id));
			    entity.set("statusId", "0");
				entity.set("createBy", createBy);
				entity.set("createDate", nowTimestamp);
			}  
			
			List<GenericValue> HrCandidateInfo = delegator.findByAnd("HrCandidateInfo", UtilMisc.toMap("name", candidateId_dictText),null, false);
			GenericValue person =EntityUtil.getFirst(HrCandidateInfo);
			String candidateId = person.getString("id");
			
			List<GenericValue> departmentInfo = delegator.findByAnd("HrDepartment", UtilMisc.toMap("name", departmentId_dictText),null, false);
			GenericValue department =EntityUtil.getFirst(departmentInfo);
			String departmentId = department.getString("departmentId");
			
			String position = ExcelPoiUtils.getDataDictionaryCode(delegator, "POSITION",position_dictText);
			String workingHours = ExcelPoiUtils.getDataDictionaryCode(delegator, "WORK_TYPE",workingHours_dictText);
			Timestamp arrivalTimeTimestamp =UtilDateTime.toTimestamp(arrivalTime);
			
			entity.set("candidateId", candidateId);
			entity.set("departmentId", departmentId);
			entity.set("position", position);
			entity.set("contractPeriod", contractPeriod);
			entity.set("probationPeriod", probationPeriod);
			entity.set("workingHours", workingHours);
			entity.set("annualSalary", annualSalary);
			entity.set("monthlySalary", monthlySalary);
			entity.set("arrivalTime", arrivalTimeTimestamp);
			
			toBeStore.add(entity);
			

			
		}
	    
	    delegator.storeAll(toBeStore);
	    result.put("messageList", messageList);
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    /**
     * 导出
     */

    public static Map<String, Object> exportXls(DispatchContext dctx, Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	String ids = (String) context.get("ids");
	List<String> baseIdList = FastList.newInstance();
	if (UtilValidate.isNotEmpty(ids)) {
	    baseIdList = Arrays.asList(ids.split(";"));
	}
	Map<String, Object> result = ServiceUtil.returnSuccess();

	EntityCondition mainCond = null;
	List<EntityCondition> andExprs = FastList.newInstance();
	//andExprs.add(EntityCondition.makeCondition("parentProductId", EntityOperator.EQUALS, "_NA_"));
	if (UtilValidate.isNotEmpty(baseIdList))
	    andExprs.add(EntityCondition.makeCondition("id", EntityOperator.IN, baseIdList));
	if (andExprs.size() > 0)
	    mainCond = EntityCondition.makeCondition(andExprs, EntityOperator.AND);

	try {
	    List<GenericValue> entityList = delegator.findList("HrOffer", mainCond, null, null, null, true);

	    List<Map<String, Object>> list = FastList.newInstance();
	    Map<String, Object> keyMap = FastMap.newInstance();
	    keyMap.put("0", "id");
	    keyMap.put("1", "candidateId_dictText");
	    keyMap.put("2", "departmentId_dictText");
	    keyMap.put("3", "position_dictText");
	    keyMap.put("4", "contractPeriod");
	    keyMap.put("5", "probationPeriod");
	    keyMap.put("6", "workingHours_dictText");
	    keyMap.put("7", "annualSalary");
	    keyMap.put("8", "monthlySalary");
	    keyMap.put("9", "arrivalTime");
	    
	    String headers = "编号,应聘者,部门,职位,合同期（年）,试用期（月）,工时方式,年薪,月薪,预期报到日期";
	    result.put("headers", headers);
	    
	    
	    

	    for (GenericValue entity : entityList) {
		Map<String, Object> map = FastMap.newInstance();
		String id = entity.getString("id");
		
		String candidateId = entity.getString("candidateId");
		String departmentId = entity.getString("departmentId");
		String position = entity.getString("position");
		String contractPeriod = entity.getString("contractPeriod");
		String probationPeriod = entity.getString("probationPeriod");
		String workingHours = entity.getString("workingHours");
		String annualSalary = entity.getString("annualSalary");
		String monthlySalary = entity.getString("monthlySalary");
		Timestamp arrivalTime = entity.getTimestamp("arrivalTime");
		
		
	    //candidateId
		List<GenericValue>candidateIdInfo = delegator.findByAnd("HrCandidateInfo", UtilMisc.toMap("id", candidateId),null, false);
		GenericValue candidateIdpartment =EntityUtil.getFirst(candidateIdInfo);
		String candidateId_dicText = candidateIdpartment.getString("name");
		
		//departmentId
		List<GenericValue> afterDepartmentInfo = delegator.findByAnd("HrDepartment", UtilMisc.toMap("departmentId", departmentId),null, false);
		GenericValue afterDepartment =EntityUtil.getFirst(afterDepartmentInfo);
		String departmentId_dicText = afterDepartment.getString("name");
		
		String position_dictText = ExcelPoiUtils.getDataDictionaryDescription(delegator, "POSITION",position);
		String workingHours_dictText = ExcelPoiUtils.getDataDictionaryDescription(delegator, "WORK_TYPE",workingHours);
		
		map.put("id", id);
		map.put("candidateId_dictText", candidateId_dicText);
		map.put("departmentId_dictText", departmentId_dicText);
		map.put("position_dictText", position_dictText);
		map.put("contractPeriod", contractPeriod);
		map.put("probationPeriod", probationPeriod);
		map.put("workingHours_dictText", workingHours_dictText);
		map.put("annualSalary", annualSalary);
		map.put("monthlySalary", monthlySalary);
		map.put("arrivalTime", arrivalTime);

		list.add(map);
	    }
	    result.put("list", list);
	    result.put("keyMap", keyMap);
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    
}
